import { Reducer } from 'redux';
import { Effect } from 'dva';
import { User } from '@/domains/user';
import { ArticleType } from '@/domains/article';
import { queryAccount, queryApplicationList, queryArticleList, queryProjectList } from './service';

export interface StateType {
  account: User | null;
  articleList: ArticleType[];
  applicationList: any[];
  projectList: any[];
}

export interface ModelType {
  namespace: string;
  state: StateType;
  effects: {
    fetchAccount: Effect;
    fetchArticleList: Effect;
    fetchApplicationList: Effect;
    fetchProjectList: Effect;
  };
  reducers: {
    save: Reducer;
  };
}

const model: ModelType = {
  namespace: 'accountCenter',

  state: {
    account: null,
    articleList: [],
    applicationList: [],
    projectList: [],
  },

  effects: {
    *fetchAccount({ payload, callback }, { call, put }) {
      const account = yield call(queryAccount, payload);
      if (account) {
        yield put({ type: 'save', payload: { account } });
        callback && callback();
      }
    },
    *fetchArticleList({ payload, callback }, { call, put }) {
      const articleList = yield call(queryArticleList, payload);
      if (articleList && articleList.length) {
        yield put({ type: 'save', payload: { articleList } });
        callback && callback();
      }
    },
    *fetchApplicationList({ payload, callback }, { call, put }) {
      const applicationList = yield call(queryApplicationList, payload);
      if (applicationList && applicationList.length) {
        yield put({ type: 'save', payload: { applicationList } });
        callback && callback();
      }
    },
    *fetchProjectList({ payload, callback }, { call, put }) {
      const projectList = yield call(queryProjectList, payload);
      if (projectList && projectList.length) {
        yield put({ type: 'save', payload: { projectList } });
        callback && callback();
      }
    },
  },

  reducers: {
    save(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};

export default model;
